import { defineStore } from "pinia";
import type { Blog, NavItem } from "~/types";
import { StyleProvider, Themes } from "@varlet/ui";
function initTheme() {
  if (process.server) return "light";
  const theme = localStorage.getItem("theme");
  return theme || "light";
}
export const useAppStore = defineStore("app", {
  state: () => ({
    closeNav: false,
    artical: undefined as Blog | undefined,
    articalNavList: new Array<NavItem>(),
    articalSelectNavId: undefined as string | undefined,
    _token: undefined as string | undefined,
    expireTime: undefined as number | undefined,
    cache: new Map<string, any>(),
    theme: initTheme(),
    goodList: [] as number[],
    showDetails: false,
    closeDetails: undefined as undefined | Function,
    editArtical: undefined as undefined | Function,
  }),
  getters: {
    token(): string | undefined {
      if (process.server) return undefined;
      const token = this._token;
      const expireTime = this.expireTime;
      if (expireTime && Number(expireTime) < Date.now()) {
        return undefined;
      }
      return token || undefined;
    },
    isDarkTheme(): boolean {
      return this.theme === "dark";
    },
  },
  actions: {
    saveGoods() {
      if (process.client) {
        localStorage.setItem("goodList", JSON.stringify(this.goodList));
      }
    },
    loadGoods() {
      if (process.client) {
        const goodList = localStorage.getItem("goodList");
        if (goodList) {
          this.goodList = JSON.parse(goodList);
        }
      }
    },
    setArtical(artical: Blog) {
      this.artical = JSON.parse(JSON.stringify(artical));
    },
    clearArtical() {
      this.artical = undefined;
    },
    logout() {
      this._token = undefined;
    },
    setToken(token: string, expireTime: number) {
      this._token = token;
      this.expireTime = expireTime;
    },
    save(key: string, data: any) {
      this.cache.set(key, data);
    },
    read(key: string) {
      return this.cache.get(key);
    },
    changeTheme(theme?: "light" | "dark") {
      this.theme = theme || (this.theme === "light" ? "dark" : "light");
      StyleProvider(this.theme === "light" ? null : Themes.dark);
      if (process.client) {
        localStorage.setItem("theme", this.theme);
      }
    },
  },
  persist: process.client && {
    storage: localStorage,
    paths: ["_token"],
  },
});
